<template>
  <!---搜索表单-->
    <div class="search-div">
        <el-form label-width="70px" size="small">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="班级名称">
                        <el-input v-model="queryDto.name" style="width: 100%" placeholder="请输入班级名称"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="年级">
                        <el-select v-model="queryDto.grade" placeholder="请选择年级" style="width: 100%">
                            <el-option v-for="grade in gradeOptions" :key="grade.value" :label="grade.label"
                                       :value="grade.label"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="学院">
                        <el-select v-model="queryDto.collegeId" style="width: 100%" placeholder="请选择所属学院"
                                   @change="handleCollegeChange">
                            <el-option v-for="item in collegeList" :key="item.id" :value="item.id"
                                       :label="item.name"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="专业">
                        <el-select v-model="queryDto.majorId" placeholder="请先选择学院" style="width: 100%">
                            <el-option v-for="item in majorList" :key="item.id" :value="item.id"
                                       :label="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchClasses"> 搜索</el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>
    </div>

  <!--添加按钮-->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <el-dialog v-model="dialogVisible" title="添加或修改" width="30%" @close="handleDialogClose">
        <el-form label-width="120px" :model="classes" ref="classesForm" :rules="rules">
            <el-form-item label="班级名称" prop="name">
                <el-input v-model="classes.name"/>
            </el-form-item>
            <el-form-item label="年级" prop="grade">
                <el-select v-model="classes.grade" placeholder="请选择年级" style="width: 40%">
                    <el-option v-for="grade in gradeOptions" :key="grade.value" :label="grade.label"
                               :value="grade.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属学院">
                <el-select v-model="classes.collegeId" placeholder="请选择所属学院" @change="handleCollegeChange">
                    <el-option v-for="item in collegeList" :key="item.id" :value="item.id"
                               :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="所属专业" prop="majorId">
                <el-select v-model="classes.majorId" placeholder="请选择所属专业">
                    <el-option v-for="item in majorList" :key="item.id" :value="item.id"
                               :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="班主任" prop="headTeacherId">
                <el-select v-model="classes.headTeacherId" filterable placeholder="请先选择学院">
                    <el-option v-for="item in teacherList" :key="item.id" :value="item.id"
                               :label="item.name"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!--查看课程-->
    <el-dialog v-model="dialogVisibleCourse" title="查看课程" width="90%" @close="handleClose">
        <el-button type="primary" size="small" @click="refreshCourses"> 刷新</el-button>
        <el-table :data="courses" v-loading="loading" :default-sort="{prop: 'academicYear', order: 'ascending'}"
                  height="400">
            <el-table-column type="index" label="序号" width="55"/>
            <el-table-column prop="courseName" label="课程名称" width="240px"/>
            <el-table-column prop="courseCode" label="课程代码"/>
            <el-table-column prop="courseCredits" label="课程学分"/>
            <el-table-column prop="academicYear" #default="scope" label="学年" sortable min-width="100px">
                {{ yearOptions[scope.row.academicYear] }}
            </el-table-column>
            <el-table-column prop="semester" #default="scope" label="学期">
                <el-tag :type="scope.row.semester == 1?'danger':'success'">{{
                    semesterOptions[scope.row.semester]
                    }}
                </el-tag>
            </el-table-column>
            <el-table-column prop="courseOwnershipName" min-width="100px" label="课程归属"/>
            <el-table-column prop="courseCategoryName" min-width="100px" label="课程类别"/>
            <el-table-column prop="courseNatureName" min-width="100px" label="课程性质"/>
        </el-table>
    </el-dialog>

  <!---数据表格-->
    <el-table :data="list" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="60px" align="center"/>
        <el-table-column prop="name" label="班级名称" min-width="200px"/>
        <el-table-column prop="grade" label="入学年份" width="90px"/>
        <el-table-column prop="collegeName" label="所属学院" width="170px"/>
        <el-table-column prop="majorName" label="所属专业" width="240px"/>
        <el-table-column prop="headTeacherName" label="班主任" width="90px"/>
        <el-table-column prop="headcount" label="班级人数" width="90px" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="160px" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="160px" align="center"/>
        <el-table-column label="操作" align="center" #default="scope" fixed="right" width="220px">
            <el-button type="success" size="small" @click="showCourse(scope.row)">查看课程</el-button>
            <el-button type="primary" size="small" @click="editClasses(scope.row)"> 修改</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row)"> 删除</el-button>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
                   :page-sizes="[5, 10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
                   layout="total, sizes, prev, pager, next" :total="total"/>
</template>

<!-- script部分修改内容 -->
<script setup>
import {onMounted, ref} from 'vue'
import {DeleteClassesById, GetClassesListByPage, SaveClasses, UpdateClasses} from '@/api/classes'
import {ElMessage, ElMessageBox} from 'element-plus'
import {GetMagorListByCollegeId} from '@/api/major'
import {GetAllCollege} from "@/api/college";
import {GetScheduleListByMajorIdAndClassesId} from "@/api/course";
import {GetAllTeacherByCollegeId} from "@/api/teacher";

const yearOptions = {
    1: '第一学年',
    2: '第二学年',
    3: '第三学年',
    4: '第四学年'
};
const semesterOptions = {
    1: '秋季学期',
    2: '春季学期'
};

const courses = ref([]); // 这是您的课程数组
const dialogVisibleCourse = ref(false)
const teacherList = ref([])
const loading = ref(false)
const classesId = ref('')
// 刷新课程列表
const refreshCourses = async () => {
    courses.value = []
    loading.value = true
    setTimeout(findCourses, 500); // 500毫秒后调用findCourses函数
}

const findCourses = async () => {
    const {data} = await GetScheduleListByMajorIdAndClassesId(classesId.value)
    courses.value = data
    loading.value = false; // 加载完成后，设置加载状态为false
}

const defaultCourse = {
    classesId: '',
    courseId: '',
    teacherId: '',
    courseName: '',
    teachingClassId: '',
    teachingClassName: '',
    academicYear: '',
    semester: ''
}

const course = ref(defaultCourse)

const handleClose = async () => {
    dialogVisibleCourse.value = false
    courses.value = []
}

//查看课程
const showCourse = async row => {
    classesId.value = row.id
    const {data} = await GetScheduleListByMajorIdAndClassesId(row.id); // 从后端获取课程数据
    courses.value = data
    dialogVisibleCourse.value = true; // 显示课程
}

const collegeList = ref([])
const majorList = ref([])

const findAllCollegeList = async () => {
    const {data} = await GetAllCollege()
    collegeList.value = data
}
// 处理学院选择变化的方法
const handleCollegeChange = async (collegeId) => {
    classes.value.majorId = ''
    classes.value.headTeacherId = ''
    await loadTeachersByCollege(collegeId)
    // 根据学院ID查询专业
    await fetchMajorsByCollegeId(collegeId)
}
const fetchMajorsByCollegeId = async (collegeId) => {
    const {data} = await GetMagorListByCollegeId(collegeId)
    majorList.value = data
}
const loadTeachersByCollege = async (collegeId) => {
    const {data} = await GetAllTeacherByCollegeId(collegeId)
    teacherList.value = data
}

// 删除数据
const deleteById = row => {
    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const {code} = await DeleteClassesById(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            pageParams.value.page = 1
            await fetchData()
        }
    })
}

// 修改按钮点击事件处理函数
const editClasses = async row => {
    classes.value = row
    await fetchMajorsByCollegeId(row.collegeId)
    await loadTeachersByCollege(row.collegeId)
    dialogVisible.value = true
}


//表单数据模型
const defaultForm = {
    name: '',
    grade: '',
    collegeId: '',
    majorId: '',
    headTeacherId: '',
}

const classes = ref(defaultForm) // 使用ref包裹该对象，使用reactive不方便进行重置
const classesForm = ref('classesForm')
const handleDialogClose = () => {
    classes.value = {...defaultForm}; // 重置数据为默认值
    dialogVisible.value = false
    classesForm.value.clearValidate();
}
// 添加角色
const submit = async () => {
    // 调用表单实例的方法
    classesForm.value.validate(async (valid) => {
        if (valid) {
            if (!classes.value.id) {
                const {code} = await SaveClasses(classes.value)
                if (code === 200) {
                    dialogVisible.value = false
                    ElMessage.success('操作成功')
                    await fetchData()
                }
            } else {
                const {code} = await UpdateClasses(classes.value)
                if (code === 200) {
                    dialogVisible.value = false
                    ElMessage.success('操作成功')
                    await fetchData()
                }
            }
        } else {
            ElMessage.error('表单验证失败，请检查输入');
            return false;
        }
    })
}

// 分页条总记录数
let total = ref(0)
// 定义表格数据模型
let list = ref([])
// 控制对话是否展示的变量
const dialogVisible = ref(false)
//进入添加
const addShow = () => {
    dialogVisible.value = true
}
//分页数据
const pageParamsForm = {
    page: 1, // 页码
    limit: 10, // 每页记录数
}
const pageParams = ref(pageParamsForm) // 将pageParamsForm包装成支持响应式的对象
// 搜索表单数据
const queryDto = ref({
    name: '',
    grade: '',
    collegeId: '',
    majorId: ''
})
const gradeOptions = ref([
    {label: '2019级', value: '2019'},
    {label: '2020级', value: '2020'},
    {label: '2021级', value: '2021'},
    {label: '2022级', value: '2022'},
    {label: '2023级', value: '2023'},
    {label: '2024级', value: '2024'},
    // 在这里添加更多的年级选项
])
// 页面加载完毕以后请求后端接口获取数据
onMounted(async () => {
    await fetchData()
    await findAllCollegeList()
    await fetchMajorsByCollegeId()
})
// 搜索按钮点击事件处理函数
const searchClasses = () => {
    fetchData()
}
// 重置按钮点击事件处理函数
const resetData = async () => {
    queryDto.value = {}
    await fetchData()
    await fetchMajorsByCollegeId()
}

// 远程调用后端分页查询接口
const fetchData = async () => {
    const {data} = await GetClassesListByPage(
        pageParams.value.page,
        pageParams.value.limit,
        queryDto.value
    )
    list.value = data.list
    total.value = data.total
}
const rules = {
    name: [{required: true, message: '请输入班级名称', trigger: 'blur'}],
    grade: [{required: true, message: '请选择年级', trigger: 'change'}],
    majorId: [{required: true, message: '请选择专业', trigger: 'change'}],
    headTeacherId: [{required: true, message: '请选择班主任', trigger: 'change'}],
    teacherId: [{required: true, message: '请选择课程老师', trigger: 'change'}]
}
</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}
</style>
